# coding:utf-8
"""
Author: 11203
Date:  16:42
Name: logs_utils
日志工具类
"""
import logging
import logging.handlers
import os

from flask import Flask, request


# 自定义日志格式类
class CFormatter(logging.Formatter):
    # 自定义日志输出格式
    def format(self, record):
        # 日志要记录请求地址
        record.url = request.url
        # 要记录远程请求IP
        record.remote_addr = request.remote_addr
        # 设置好日志的格式后返回
        return super().format(record)


# 创建日志记录器
def create_logger(app: Flask):
    logging_file_dir = app.config['LOGGING_FILE_DIR']
    logging_file_max_bytes = app.config['LOGGING_FILE_MAX_BYTES']
    logging_file_backup = app.config['LOGGING_FILE_BACKUP']
    logging_level = app.config['LOGGING_LEVEL']

    # %(asctime)s 时间格式化
    # %(levelname)s 日志等级
    # %(module)s 日志来源的模块名称
    # %(lineno)d 日志行号
    # %(message)s 日志信息
    # >>>> %(remote_addr)s 、%(url)s 为重写formatter类后的自定义日志格式属性, 参照CFormatter类

    # --------- 写入文件的日志格式  ---------
    c_formater = CFormatter(
        '[%(asctime)s] %(remote_addr)s request url -> %(url)s\t%(levelname)s at %(module)s %(lineno)d : %(message)s')
    # 如果目录不存在，则创建目录
    if not os.path.exists(logging_file_dir):
        os.mkdir(logging_file_dir)

    flask_file_handler = logging.handlers.RotatingFileHandler(filename=os.path.join(logging_file_dir,'shopping.log'),
                                                              maxBytes=logging_file_max_bytes,
                                                              backupCount=logging_file_backup
                                                              )

    flask_file_handler.setFormatter(c_formater)

    # 获取日志对象
    flask_logger = logging.getLogger('dongbaoshop')
    app.logger = flask_logger
    flask_logger.addHandler(flask_file_handler)
    flask_logger.setLevel(logging_level)

    # --------- 显示在控制台中  ---------
    flask_console_handler = logging.StreamHandler()
    console_formatter = logging.Formatter(
        fmt='[%(asctime)s] %(remote_addr)s request url -> %(url)s\t%(levelname)s at %(module)s %(lineno)d : %(message)s')
    flask_console_handler.setFormatter(console_formatter)

    # 当项目运行在debug环境下时，才用控制台输出
    if app.debug:
        flask_logger.addHandler(flask_console_handler)


